<template>
  <div id="DefaultWeather">
    <div class="mainContainer">
      <!-- 一、输入、提示、已存储部分 -->
      <div class="search">
        <!-- 输入框 -->
        <input :class="isFocus? 'focus' : 'unfocus'"
            @focus="inputFocus"
            @blur="inputUnfocus" 
            @input="matchCity"
            type="text" 
            v-model="cityName" 
            placeholder="请输入城市名称" >
        <!-- 输入后的弹出来部分 -->
        <div class="query" v-if="flag" @click="gotoOtherCity">{{exist}}</div>
        <!-- 没有保存而提示的部分 -->
        <div class="reminder" v-if="$store.state.unsaved">暂时没有保存过城市天气信息，请查询后点击右上角"+"号保存。</div>
        <!-- 如果有保存，列表循环现实的部分 -->
        <div class="saved" v-else v-for="item in cities" :key="item.id" >
            <div class="block">
                <div class="sCity">
                    <span>{{item.city}}</span>
                    <span :title="item.adcode" ref="getTem">{{temperature[item.id-1]}}度</span>
                </div>
                <div class="fBtn">
                    <button :name="item.city" :value="item.adcode" ref="checkBtn" @click="check">查看</button>
                    <button :value="item.id" ref="deleteBtn" @click="deleteCities">删除</button>
                </div>
            </div>
        </div>
      </div>

      <!-- 二、'近期天气'部分 -->
      <div class="chart">
        <p>近期天气</p>
        <div class="weatherForecast">
            <!-- 1.文字排列的部分 -->
            <div class="text">
                <div class="days" v-for="item in dates" :key="item.id">
                    <span>{{item.week}}</span>
                    <span>{{item.date}}</span>
                    <span>{{item.dayweather}}</span>
                    <span>风力{{item.daypower}}级</span>                  
                </div>
            </div>

            <!-- 2.折线图 -->
            <div id="linegraph" style="width:100%;height:160px"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
const axios = require('axios');
import * as echarts from "echarts";

export default {
  name:'DefaultWeather',
  data(){
    return{
      cityName:'',
      isFocus:false,
      flag:false,
      tmp:'',
      exist:'',

      dates:[],
      xData:[],
      yDaytemp:[],
      yNighttemp:[],
      cities:[],
      checkCityName:'',
      checkCityCode:'',
      cityId:0,
      temperature:[], 
      /* unsaved:true */
    }
  },
  created(){
    this.showSavedCities()
    
  },
  mounted(){
   this.weatherFore()
   this.storageCities()
   this.getTemperature()
    },
  methods:{
    /* 获得已存城市条中的天气 */
    async getTemperature(){
        console.log('zaq',this.$refs.getTem.length);
        const n = this.$refs.getTem.length
        for(var i=0 ;i<n;i++){
            const code = this.$refs.getTem[i].title
            //通过编码发请求，得到温度
            const res = await axios.get(`https://restapi.amap.com/v3/weather/weatherInfo?city=${code}&extensions=base&key=76dd8c6deab6cb7638ee9a9e77ae197d`)
            console.log(res.data.lives[0].temperature);
            this.temperature[i] = res.data.lives[0].temperature
        }
        console.log('aaa',this.temperature);
        /* console.log(this.$refs.getTem[0].title);  */
    },


    /* 已存城市条的删除功能 */
    deleteCities(event){
        const target = event.target
        //拿到了ID
        console.log('jy',target.value);
        //操作Storage
        //获取LS中的数据
        var items = JSON.parse(localStorage.getItem('savedCities'))
        //找到要删除的对象的索引值
        var index = items.findIndex(function(obj){
            return obj.id === Number(target.value);
        });
        //从数组中删除对象
        items.splice(index,1)
        //将操作后的数据存回lS中
        localStorage.setItem('savedCities',JSON.stringify(items))
        this.showSavedCities()
    },

    /* 点击存储返回上一个页面  加载存储城市的功能 */
    showSavedCities(){
        var items = JSON.parse(localStorage.getItem('savedCities'))
        if(items != null){
            this.$store.state.unsaved = false
            this.cities = items
        }else{
            this.$store.state.unsaved = true
        }
    },

    /* 已存城市条的查看跳转功能 */
    check(event){
        const target = event.target
        this.checkCityName = target.name
        this.checkCityCode = target.value
        this.$store.commit('sendcheckCityName',this.checkCityName)
        this.$store.commit('sendcheckCityCode',this.checkCityCode)

        this.$router.push('/other');
    },

    /* 从localStorage中得到数据，渲染存储的城市*/
    storageCities(){
     const items = JSON.parse(localStorage.getItem('savedCities'))
     this.cities = items
    },

    /* 发送请求加载 深色框中的 文字和图表 */
    async weatherFore(){
      /* 1. 通过默认IP查询地址 */
      const res0 = await axios.get('https://restapi.amap.com/v3/ip?key=76dd8c6deab6cb7638ee9a9e77ae197d')    
      this.address = res0.data.city
      /* 2. 通过地址名得到地区编码 */
      const res1 = await axios.get(`https://restapi.amap.com/v3/geocode/geo?address=${this.address}&key=76dd8c6deab6cb7638ee9a9e77ae197d`)
      /* 3. 通过编码获取天气 */
      const res2 = await axios.get(`https://restapi.amap.com/v3/weather/weatherInfo?city=${res1.data.geocodes[0].adcode}&extensions=all&key=76dd8c6deab6cb7638ee9a9e77ae197d`)
      const tmp = res2.data.forecasts[0].casts
      this.dates = tmp

      this.dates[0].week = '今天'
      this.dates[1].week = '明天'
      for(let i=0; i<tmp.length;i++){
        const str = this.dates[i].date
        this.dates[i].date = str.substring(5,10)
        const week = this.dates[i].week
        switch(week){
            case '1':
                this.dates[i].week = '周一';
                break;
            case '2':
                this.dates[i].week = '周二';
                break;
            case '3':
                this.dates[i].week = '周三';
                break;
            case '4':
                this.dates[i].week = '周四';
                break;
            case '5':
                this.dates[i].week = '周五';
                break;
            case '6':
                this.dates[i].week = '周六';
                break;
            case '7':
                this.dates[i].week = '周日';
                break;
        }

        /* 图表取值 */
        this.yDaytemp[i] = tmp[i].daytemp-0  /* 为了变成数字类型 */
        this.yNighttemp[i] = tmp[i].nighttemp-0
      }

      //echarts实例
      let temChart = echarts.init(document.getElementById('linegraph'))
      
      //图表设置
      let option= {
        xAxis: {          
            scale:true,
            show:false,
            data: [],
        },
        yAxis: {
            type:'value',
            show:false,    
        },
        series: [
            {
            data: this.yDaytemp,
            type: 'line',
            smooth:true,
            alimation:true,
            label:{
                show:true,
                formatter:'白{c}℃',
                fontSize:12,
                color:'#fff',
                }
            },
            {
            data: this.yNighttemp,
            type: 'line',
            smooth:true,
            alimation:true,
            label:{
                show:true,
                formatter:'晚{c}℃',
                position:'bottom',
                fontSize:12,
                color:'#fff'
                }          
            }
        ]
      }
      temChart.setOption(option)

    },
    /* 输入聚焦 */
    inputFocus(){
        this.isFocus = true
    },
    /* 不输离焦 */
    inputUnfocus(){
        this.isFocus = false
    },

    /* 通过输入地区名称 来查询/匹配 的功能 */
    async matchCity(){
            if(this.cityName !=''){
                this.flag = true 
                const res = await axios.get(`https://restapi.amap.com/v3/geocode/geo?address=${this.cityName}&key=76dd8c6deab6cb7638ee9a9e77ae197d`)
                /* 没找到 */
                if(res.data.status == '0'){
                    this.exist = '似乎没有找到你查找的城市'
                }
                /* 找到 */
                if(res.data.status == '1'){
                    this.tmp = res.data.geocodes[0].adcode
                    const res1=  await axios.get(`https://restapi.amap.com/v3/weather/weatherInfo?city=${this.tmp}&extensions=all&key=76dd8c6deab6cb7638ee9a9e77ae197d`) 
                    this.exist = res1.data.forecasts[0].city
                }
            }else{
                this.exist= ''
                this.flag = false
            }
    },

    /* 点击查询到的框，跳转到其他地区天气详情的页面 */
    gotoOtherCity(){
        if(this.exist != '似乎没有找到你查找的城市'){
            this.$router.push('/other');
        }
        this.$store.commit('setMessage',this.exist)       
        this.$store.commit('setCode',this.tmp)       
    },
  }
}
</script>

<style scoped>
#DefaultWeather{
  background-color: rgba(0,102,138,1);
  display: flex;
}
#DefaultWeather .mainContainer{
  width: 720px;
  margin: 0 auto;
}
.mainContainer input{
  height: 40px;
  width: 100%;
  margin: 20px 0;
  border: none;
  outline: none;
  appearance: none;
  font-size:16px;
  color: #fff;
  background-color:transparent 
}
.mainContainer .unfocus{
    border-bottom: solid 1px white;
}
.mainContainer .focus{
    box-shadow: 0px 3px 2px rgba(59, 59, 59, 0.3);
}
.mainContainer .input::-webkit-input-placeholder {
  color:#999
}
.mainContainer .search .reminder{
  text-align: center;
  color: #fff;
  margin: 20px 0 30px 0;
}
.mainContainer .search .query{
    width: 100%;
    padding: 20px 0;
    font-size:16px;
    color: #fff;
    background-color: rgb(0,78,113);
}
.search .saved .block{
    display: flex;
    flex:1;
    width: 100%;
    margin-bottom: 8px;
    font-size:16px;
    color: #fff;
    box-sizing: border-box;
}
.search .saved .sCity{
    display: flex;
    justify-content: space-between;
    padding: 13px 20px;
    width: 100%;
    background-color: rgb(0,78,113);
    transition: width 0.5s;
}
.saved .block .fBtn{
    display: flex;
    flex: 1;
    justify-content: space-between;
}
.saved .block button{
    display: none;
}
.search .saved .block:hover{
    cursor: pointer;
}
.search .saved .block:hover .sCity{
    width: 70%;
}
.search .saved .block:hover button{
  display: block;
  color: #fff;
  background-color: rgba(234,179,8,1);
  padding: 13px 25px;
  font-size:16px;
  border: none;
  cursor: pointer;
}
.mainContainer .search .click{
    cursor:pointer;
}
.mainContainer .chart{
    color: #fff;
    margin-top: 30px;
}
.mainContainer .chart .weatherForecast{
    background-color: rgb(0,78,113);  
    margin: 20px 0;
    border-radius: 10px;
}
.chart .weatherForecast .text{
    display: flex;
    padding: 25px 70px 0 70px;
}
.chart .weatherForecast .text .days{
    flex: 1 ;
    flex-direction: column;
}
.weatherForecast .text .days span{
    display: block;
    text-align: center;
    margin: 25px 0;
}
</style>